package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.TzUserInviteCode;
import com.yami.shop.bean.model.User;
import com.yami.shop.dao.TzUserInviteCodeMapper;
import com.yami.shop.service.TzUserInviteCodeService;
import com.yami.shop.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @author Administrator
 * @description 针对表【tz_user_invite_code】的数据库操作Service实现
 * @createDate 2024-02-28 20:48:21
 */
@Service
@Log4j2
public class TzUserInviteCodeServiceImpl extends ServiceImpl<TzUserInviteCodeMapper, TzUserInviteCode>
        implements TzUserInviteCodeService {
    @Autowired
    private UserService userService;


    @Override
    @Transactional
    public String joinInvite(String userId, String inviteCode) {

        //根据邀请码找到邀请人Id
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getInvitationCode, inviteCode);
        BaseMapper<User> baseMapper1 = userService.getBaseMapper();
        User user = baseMapper1.selectOne(queryWrapper);

        if (Objects.isNull(user) || StringUtils.equals(user.getUserId(), userId)) {
            return "邀请码无效";
        }
        user.setInvitationCode(inviteCode);

        //重复验证
        LambdaQueryWrapper<TzUserInviteCode> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TzUserInviteCode::getInviteUserId, user.getUserId());
        queryWrapper1.eq(TzUserInviteCode::getInviteeUserId, userId);
        TzUserInviteCode tzUserInviteCode1 = baseMapper.selectOne(queryWrapper1);
        if (Objects.nonNull(tzUserInviteCode1)) {
            return "已经邀请了";
        }

        //更新被邀请人的上级代理Id
        User inviteedUser = userService.getUserByUserId(userId);
        inviteedUser.setParentId(user.getUserId());

        int count1 = baseMapper1.updateById(user);
        int count2 = baseMapper1.updateById(inviteedUser);
        if (count2 == 0 && count1 == 0) {
            log.info("保存验证码失败，更新的代理用户数量{}，和被邀请用户数量：{}", count1, count2);
        }

        //同时插入关系表
        TzUserInviteCode tzUserInviteCode = new TzUserInviteCode();
        tzUserInviteCode.setInviteeUserId(inviteedUser.getUserId());
        tzUserInviteCode.setInviteTime(new Date());
        tzUserInviteCode.setIsDelete(0);
        tzUserInviteCode.setInviteCode(inviteCode);
        tzUserInviteCode.setInviteUserId(user.getUserId());
        boolean save = this.save(tzUserInviteCode);
        log.info("保存验证码关系表是否成功：{}", save);
        return null;
    }
}